export default {
	data() {
		return {
			mescroll: null,
			timeList: [], //时间列表
			seckillId: null, //选中的时间块
			seckillIndex: null, //选中时间块的index
			dataList: [], //选中时间块的商品列表
			index: null, //当前正在抢购的index,
			timer: null,
			noStartList: [],
			
			token: '',
			goodsSkuDetail: {}, // 秒杀商品详情
			cartList: [],
			cartFlag: false,
			cart_show: false,
			isShowPoint: false,
			isIphoneX: false,
			cartBottom: '0',
			address: ''
		};
	},
	watch: {
		seckillId(newName, oldName) {
			if (newName && oldName && newName != oldName) {
				this.mescroll.resetUpScroll(false);
			}
		}
	},
	computed: {
		show() {
			return this.timeList.length > 0
		},
		cartPrice() {
			return this.$store.state.cartPrice;
		},
		cartNumber() {
			if (this.$store.state.cartNumber == 0) {
				this.cart_show = false
			} else {
				this.cart_show = true
			}
			return this.$store.state.cartNumber;
		},
		cartIds() {
			return this.$store.state.cartIds;
		},
	},
	methods: {
		// 结算
		pay() {
			uni.setStorage({
				key: 'orderCreateData',
				data: {
					cart_ids: this.cartIds
				},
				success: () => {
					this.$util.redirectTo('/pages/order/payment/payment');
				}
			});
		},
		closePoint() {
			this.isShowPoint = false;
		},
		// 获取地址信息
		getAddress() {
			this.$api.sendRequest({
				url: '/api/community/getMemberCommunity',
				// data: {
				// 	token: this.token
				// },
				success: res => {
					if (res.code >= 0) {
						this.isShowPoint = false;
						this.address = res.data.full_address;
						this.latitude = res.data.latitude;
						this.longitude = res.data.longitude;
						this.SelectCart()
					} else {
						this.isShowPoint = true;
						this.cart_show = false
					}
				},
				fail: res => {
					this.$util.showToast({
						title: res.message
					})
				}
			})
		},
		// 购物车处理
		SelectCart() {
			if (this.$store.state.cartNumber != 0) {
				this.cart_show = true
			}
		},
		
		
		//获取购物车数量
		getCartCount() {
			this.$store.dispatch('getCartNumber').then((e) => {
				this.cartCount = e;
			})
		},
		// 刷新商品sku详情数据
		refreshGoodsSkuDetail(goodsSkuDetail) {
			Object.assign(this.goodsSkuDetail, goodsSkuDetail);
		},
		// 秒杀商品详情
		async getGoodsSkuDetail(item) {
			let res = await this.$api.sendRequest({
				url: '/seckill/api/seckillgoods/detail',
				async: false,
				data: {
					seckill_id: item.id
				}
			});
			
			if (res.code >= 0) {
				let data = res.data;
				if (data.goods_sku_detail != null) {
					this.goodsSkuDetail = data.goods_sku_detail;
					this.goodsSkuDetail.activity_id = item.activity_id;
					this.goodsSkuDetail.activity_type = item.activity_type;
					
					let time = new Date(res.timestamp * 1000);
					let currentTime = time.getHours() * 60 * 60 + time.getMinutes() * 60 + time.getSeconds();
					if (this.goodsSkuDetail.seckill_start_time <= currentTime && currentTime < this.goodsSkuDetail.seckill_end_time) {
						this.goodsSkuDetail.discountTimeMachine = this.$util.countDown(this.goodsSkuDetail.seckill_end_time - currentTime);
					} else if (this.goodsSkuDetail.seckill_start_time > currentTime && currentTime < this.goodsSkuDetail.seckill_end_time) {
						this.$util.showToast({
							title: "限时秒杀活动还未开始",
						});
						setTimeout(() => {
							this.$util.redirectTo('/pages/goods/detail/detail', {
								sku_id: this.goodsSkuDetail.sku_id
							}, 'redirectTo');
						}, 1000);
					} else if (currentTime < this.goodsSkuDetail.seckill_start_time && currentTime > this.goodsSkuDetail.seckill_end_time) {
						this.$util.showToast({
							title: "限时秒杀活动已结束",
						});
						setTimeout(() => {
							this.$util.redirectTo('/pages/goods/detail/detail', {
								sku_id: this.goodsSkuDetail.sku_id
							}, 'redirectTo');
						}, 1000);
					}
					
					this.goodsSkuDetail.show_price = this.goodsSkuDetail.seckill_price;
					this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
					this.goodsSkuDetail.save_price = (this.goodsSkuDetail.price - this.goodsSkuDetail.seckill_price) > 0 ? (this.goodsSkuDetail.price - this.goodsSkuDetail.seckill_price).toFixed(2) : 0;
					
					// 当前商品SKU规格
					if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
					// 商品SKU格式
					if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
					
					this.$refs.goodSkuNew.show("join_cart", this.goodsSkuDetail, () => {
						this.getCartCount();
					});
				}
			}
		},
		// 变更购物车数量
		cartNumChange(type, goods) {
			
			if (!uni.getStorageSync('token')) {
				this.$refs.login.open('/promotionpages/seckill/list/list');
				return;
			}
		
			let cartData = {
					num: 1,
					cart_id: goods.cart_id,
					sku_id: goods.sku_id,
					activity_type: goods.activity_type,
					activity_id: goods.activity_id
				},
				cartUrl = "", //类型 add--新增商品  edit--修改商品数量  delete--删除商品
				actionType,
				maxBuy = goods.max_buy,
				stock = maxBuy > 0 ? (maxBuy - goods.purchased_num) : goods.stock;
		
			var minBuy = 1;
			if (goods.min_buy > 1) minBuy = goods.min_buy;
			cartData.num = minBuy; // 最少购买量
		
			goods.unit = goods.unit || "件";
		
			if (type == 'add') {
				// 检测是否第一次加入购物车
				if (goods.cart_id) {
					actionType = "edit";
					cartUrl = '/api/cart/edit';
				} else {
					actionType = "add";
					cartUrl = '/api/cart/add';
				}
				if (stock == 0) {
					this.$util.showToast({
						title: '库存不足'
					});
					return;
				} else if (goods.cart_id && goods.num < stock) {
					cartData.num = ++goods.num;
				} else {
					if (maxBuy > 0 && (goods.purchased_num + goods.num) >= maxBuy) {
						this.$util.showToast({
							title: '该商品每人限购' + maxBuy + goods.unit + '，您已购买了' + goods.purchased_num + goods.unit
						});
						return;
					}
		
					if (maxBuy > 0 && goods.num > 0 && goods.num + cartData.num > maxBuy) {
						var diff = maxBuy - goods.num;
						if (diff > 0) {
							this.$util.showToast({
								title: '该商品每人限购' +
									maxBuy +
									goods.unit +
									'，购物车已加入了' +
									goods.num +
									goods.unit +
									'，还能购买' +
									diff +
									goods.unit
							});
						} else {
							this.$util.showToast({
								title: '该商品每人限购' + maxBuy + goods.unit
							});
						}
						return;
					}
				}
		
			} else if (type == 'minus') {
				cartData.num = goods.num - 1 ? goods.num - 1 : 0;
				cartUrl = cartData.num > 0 ? '/api/cart/edit' : '/api/cart/delete';
				actionType = cartData.num > 0 ? 'edit' : 'delete';
			}
		
			if (this.cartFlag) return false;
			this.cartFlag = true;
		
			this.shopDataChange(cartData);
		
			this.$api.sendRequest({
				url: cartUrl,
				data: cartData,
				success: res => {
					if (res.code >= 0) {
						if (res.data > 0) {
							this.$store.dispatch('getCartNumber');
							this.$store.dispatch('getCartPrice');
							this.$store.dispatch('getCartIds');
							
							if (actionType == "edit") {
								this.cartFlag = false;
								return false;
							}
							
							goods.cart_id = actionType == 'add' ? res.data : '';
							if (actionType == 'add') {
								this.$util.showToast({
									title: '加入购物车成功'
								});
							}
						} else {
							cartData.num = goods.num;
							this.$util.showToast({
								title: res.message
							});
						}
					}
		
					this.cartFlag = false;
				}
			});
		
		},
		shopDataChange(data) {
			for (var i = 0; i < this.dataList.length; i++) {
				var item = this.dataList[i];
				if (data.sku_id == item.sku_id) {
					item.num = data.num;
					item.cart_id = data.cart_id;
				}
			}
			this.$forceUpdate();
		},
		
		
		
		goodsImg(imgStr) {
			let imgs = imgStr.split(',');
			return imgs[0] ? this.$util.img(imgs[0], { size: 'mid' }) : this.$util.getDefaultImage().default_goods_img;
		},
		//时间转换
		transformSeckillTime(time)
		{
		   time = parseFloat(time);
		   var hour = parseInt(time / 3600);
		   var minute = parseInt((time % 3600 ) / 60);
		   var second = parseInt(time % 60);
		
		   if(hour < 10) hour = '0'+hour;
		   if(minute < 10) minute = '0'+minute;
		   if(second < 10) second = '0'+second;
		
		   return hour+':'+minute;
		},
		isEnd(isShow) {
			if (!isShow) return;
			this.$util.showToast({
				title: "限时秒杀活动已结束",
			});
		},
		getTimeList() {
			this.$api.sendRequest({
				url: '/seckill/api/seckill/lists',
				success: res => {
					let data = res.data;
					if (!data) return;
					let time = new Date(res.timestamp * 1000);
					let newTimes = time.getHours() * 60 * 60 + time.getMinutes() * 60 + time.getSeconds();
					var tempList = Object.values(data.list);
					tempList.forEach((v, k) => {
						if (v.seckill_start_time <= newTimes && newTimes < v.seckill_end_time) {
							v.isNow = true;
							this.seckillId = v.id;
							this.index = k;
							this.seckillIndex = k;
						} else {
							v.isNow = false;
						}
					});
					this.timeList = tempList;
				
					if (tempList.length) {
						let now = Math.round(new Date() / 1000), // 当前时间戳
							start = Math.round(new Date(new Date().toLocaleDateString()).getTime() / 1000), // 当天0点时间戳
							second = now - start;
							
						for (let i = 0; i < tempList.length; i++) {
							if (newTimes < tempList[i].seckill_start_time && i == 0) {
								this.seckillId = tempList[i].id;
								this.index = i;
								this.seckillIndex = i;
							} else if (newTimes < tempList[i].seckill_start_time && newTimes > tempList[i - 1].seckill_end_time && i !=
								0) {
								this.seckillId = tempList[i].id;
								this.index = i;
								this.seckillIndex = i;
							} else if (i == tempList.length - 1 && newTimes > tempList[i].seckill_end_time) {
								this.seckillId = tempList[i].id;
								this.index = i;
								this.seckillIndex = i;
							}
							
							if (second < tempList[i].seckill_start_time) {
								let temp = tempList[i];
									temp.index = i;
								this.noStartList.push(temp);
							}
						}
						if (this.noStartList.length) {
							this.autoEvent();
						}
					}
					var self = this;

					setInterval(function() {
						self.getExpirationTime();
					}, 1000);
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				}
			});
		},
		getData(mescroll) {
			this.mescroll = mescroll;
			this.$api.sendRequest({
				url: '/seckill/api/seckillgoods/page',
				data: {
					page_size: mescroll.size,
					page: mescroll.num,
					seckill_time_id: this.seckillId
				},
				success: res => {
					this.showEmpty = true;
					let newArr = []
					let msg = res.message;
					if (res.code == 0 && res.data) {
						newArr = res.data.list;
					} else {
						this.$util.showToast({
							title: msg
						})
					}
					mescroll.endSuccess(newArr.length);
					//设置列表数据
					if (mescroll.num == 1) this.dataList = []; //如果是第一页需手动制空列表
					this.dataList = this.dataList.concat(newArr); //追加新数据
					this.getCartData();
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				},
				fail() {
					//联网失败的回调
					mescroll.endErr();
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				}
			});
		},
		getCartData() {
			this.$api.sendRequest({
				url: '/api/cart/lists',
				success: res => {
					if (res.code >= 0) {
						this.cartList = res.data;

						for (let goods_index in this.dataList) {
							let goods_item = this.dataList[goods_index],
								activity_type = goods_item.activity_type,
								activity_id = goods_item.activity_id,
								goods_id = goods_item.goods_id,
								num = 0,
								cart_id = '';
		
							for (let cart_index in this.cartList) {
								let cart_item = this.cartList[cart_index];
								
								if (activity_type == cart_item.activity_type) {
									if (activity_id == cart_item.activity_id && goods_id == cart_item.goods_id) {
										num += cart_item.num;
										cart_id = cart_item.cart_id;
									}
								}
							}
							goods_item.num = num;
							goods_item.cart_id = cart_id;
		
							if (typeof goods_item.num === 'undefined' || goods_item.num === null) {
								goods_item.num = 0;
							}
						}
						this.$forceUpdate();
					}
				}
			});
		},
		getExpirationTime() {
			var timeListData = this.timeList,
				currDate = new Date(),
				dateStr = currDate.toLocaleDateString(),
				expirationTime,
				nowTime,
				obj;

			for (let i in timeListData) {
				if (timeListData[i].isNow) {
					this.ident = true;
					nowTime = Date.parse(currDate);
					expirationTime = Date.parse(dateStr) + parseInt(timeListData[i].seckill_end_time) * 1000;
					let endSeconds = (expirationTime - nowTime) / 1000;
					obj = this.$util.countDown(endSeconds);
					this.hour = obj.h;
					this.minute = obj.i;
					this.second = obj.s;
					if (endSeconds == 0) {
						let next = parseInt(i) + 1;
						if (next < timeListData.length) this.index = next;
						this.timeList[i].isNow = false;
					}
					return false;
				}
			}
			this.ident = false;
		},
		ontabtap(e, f) {
			this.seckillId = e;
			this.seckillIndex = f;
		},
		//跳转到详情页
		toGoodsDetail(id, index) {
			if (this.seckillIndex < this.index) {
				this.$util.showToast({
					title: "秒杀活动已结束！",
				});
				return;
			}
			if (this.seckillIndex > this.index) {
				this.$util.showToast({
					title: "秒杀活动还未开启，敬请期待！",
				});
				return;
			}
			this.$api.sendRequest({
				url: '/api/config/time',
				data: {},
				success: res => {

					let time = new Date(res.timestamp * 1000);
					let newTimes = time.getHours() * 60 * 60 + time.getMinutes() * 60 + time.getSeconds();
					if (this.timeList[index].seckill_start_time <= newTimes && newTimes < this.timeList[index].seckill_end_time) {
						this.timeList[index].isNow = true;
					} else {
						this.timeList[index].isNow = false;
					}

					this.$forceUpdate();

					if (!this.timeList[index].isNow){
						this.$util.showToast({
							title: "秒杀活动即将开启，敬请期待！",
						});
						return;
					} 
					this.$util.redirectTo('/promotionpages/seckill/detail/detail', {
						seckill_id: id
					});

				}
			});
		},
		imageError(index) {
			this.dataList[index].sku_image = this.$util.getDefaultImage().default_goods_img;
			this.$forceUpdate();
		},
		autoEvent(){
			this.timer = setInterval(() => {
				let now = Math.round(new Date() / 1000), // 当前时间戳
					start = Math.round(new Date(new Date().toLocaleDateString()).getTime() / 1000), // 当天0点时间戳
					second = now - start;
					for (let i = 0; i < this.noStartList.length; i++) {
						let item = this.noStartList[i];
						if (second > item.seckill_start_time && !item.isNow) {
							this.seckillId = item.seckill_id;
							this.index = item.index;
							this.timeList[item.index].isNow = true;
							if (this.timeList[item.index - 1] != undefined) {
								this.timeList[item.index - 1].isNow = false;
							}
							this.noStartList.splice(i);
						}
					}
					
					if (this.noStartList.length == 0) {
						clearInterval(this.timer);
					}
			}, 1000)
		},
		goodsTag(data){
			switch (data.recommend_way) {
				case 1:
					return '新品';
				break;
				case 2:
					return '精品';
				break;
				case 3:
					return '推荐';
				break;
				default: 
					return '';
			}
		}
	},
	onShareAppMessage(res) {
		var title = '一大波的秒杀福利就要开始了，真的不来看看嘛';
		var path = '/promotionpages/seckill/list/list';
		return {
			title: title,
			path: path,
			success: res => {},
			fail: res => {}
		};
	},
	onHide() {
		clearInterval(this.timer);
	}
};
